package com.fwmagic.rpc.transport;

import com.fwmagic.rpc.service.pojo.RpcRequest;
import com.sun.org.apache.regexp.internal.REUtil;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class RpcNetTransport {

    private String host;

    private Integer port;

    public RpcNetTransport() {
    }

    public RpcNetTransport(String host, Integer port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 创建一个新的socket连接
     *
     * @return
     * @throws IOException
     */
    public Socket newSocket() throws IOException {
        Socket socket;

        try {
            socket = new Socket(host, port);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("创建Socket连接失败！");
        }
        return socket;
    }

    public Object sendRequest(Socket socket,RpcRequest rpcRequest) throws IOException {
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        try {
            //传输类信息，请求远程执行结果
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(rpcRequest);
            outputStream.flush();

            //接收返回的结果
            inputStream = new ObjectInputStream(socket.getInputStream());
            Object result = inputStream.readObject();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送数据异常", e);
        } finally {
            //关闭流
            if (inputStream != null) inputStream.close();
            if (outputStream != null) outputStream.close();
        }
    }
}
